/**
 * 
 */
package cn.edu.bjtu.alex.rewrite.components;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Map.Entry;

import cn.edu.bjtu.alex.rewrite.Context;



/**
 * @author alex
 *
 */
public abstract class SortSupport<V> extends BaseComponent implements Iterator<Entry<String, V>>{
	private Queue<Entry<String, V>> _queue; 
	public SortSupport(Context ctx) {
		super(ctx);
	}
	protected abstract int sortBy(String key);
	protected abstract boolean shouldAdd(Entry<String, V> entry);
	final protected void sortMap(Map<String,V> map){
		_queue = new PriorityQueue<>(idComparator);
		for(Entry<String, V> termEntry : map.entrySet()) {
			if(shouldAdd(termEntry)){
				_queue.add(termEntry);	
			}
				
		}
	}
	final private Comparator<Entry<String, V>> idComparator = new Comparator<Entry<String, V>>(){
	        public int compare(Entry<String, V> c1, Entry<String, V> c2) {
	            return (int) (sortBy(c1.getKey()) - sortBy(c2.getKey()));
	        }
	};
    final public boolean hasNext(){
    		return _queue.peek() != null;
    }

    public final Entry<String, V> next(){
    		return _queue.poll();
    }

	

}
